//Copyright 2009 Dominik Punz
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.

#ifndef jniReference_h__
#define jniReference_h__

#include "jniEnvironment.h"

template<typename T>
class CJniLocalReference
{
public:
  CJniLocalReference() : mLocalReference(0) { }
  CJniLocalReference(T localReference) : mLocalReference(localReference) { }

  virtual ~CJniLocalReference()
  {
    Release();
  }

  CJniLocalReference& operator=(const T& other)
  {
    Attach(other);
    return *this;
  }

  operator bool() 
  {
    return mLocalReference != 0;
  }

  T Get() 
  {
    return mLocalReference;
  }

  void Attach(const T& other)
  {
    Release();
    mLocalReference = other;
  }

  T Detach()
  {
    T tmp = mLocalReference;
    mLocalReference = 0;
    return tmp;
  }

  void Release()
  {
    if (mLocalReference)
      jni.Env()->DeleteLocalRef(mLocalReference);
    mLocalReference = 0;
  }

private:
  // don't allow to copy or to pass by reference to avoid wrong usage
  CJniLocalReference(const CJniLocalReference& other) { }
  CJniLocalReference& operator=(const CJniLocalReference& other) { }

private:
  CJniEnvironment jni;
  T mLocalReference;
};

#endif // jniReference_h__